package com.rainbow.gray.framework.decorator;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.ConfigurableEnvironment;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.cloud.nacos.ribbon.NacosServerList;
import com.rainbow.gray.framework.context.PluginContextAware;
import com.rainbow.gray.framework.filter.servers.loadbalance.LoadBalanceListenerExecutor;

//每5秒 获取nacos server list时，过滤掉不要的服务实例，框架本身核心就是使用这个流程
public class NacosServerListDecorator extends NacosServerList {
	
	private static final Logger LOG = LoggerFactory.getLogger(NacosServerListDecorator.class);
	
    private ConfigurableEnvironment environment;

    private LoadBalanceListenerExecutor loadBalanceListenerExecutor;

    public NacosServerListDecorator(NacosDiscoveryProperties nacosDiscoveryProperties) {
        super(nacosDiscoveryProperties);
    }

    @Override
    public List<NacosServer> getInitialListOfServers() {
        List<NacosServer> servers = super.getInitialListOfServers();

        filter(servers);

        return servers;
    }

    @Override
    public List<NacosServer> getUpdatedListOfServers() {
        List<NacosServer> servers = super.getUpdatedListOfServers();
        LOG.info("NacosServerListDecorator 过滤服务器之前:" + servers);
        filter(servers);
        LOG.info("NacosServerListDecorator 过滤服务器之后:" + servers);
        return servers;
    }

    private void filter(List<NacosServer> servers) {
        Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment);
        if (discoveryControlEnabled) {
            String serviceId = getServiceId();
            loadBalanceListenerExecutor.onGetServers(serviceId, servers);
        }
    }

    public void setEnvironment(ConfigurableEnvironment environment) {
        this.environment = environment;
    }

    public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) {
        this.loadBalanceListenerExecutor = loadBalanceListenerExecutor;
    }
}